package com.nowcoder.community.service;

import com.nowcoder.community.dao.elasticsearch.DiscussPostRepository;
import com.nowcoder.community.entity.DiscussPost;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author 韩
 * @version 1.0
 */
@Service
public class ElasticsearchService {

    @Autowired
    private DiscussPostRepository discussPostRepository;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    public void save(DiscussPost discussPost){
        discussPostRepository.save(discussPost);
    }

    public void delete(int postId){
        discussPostRepository.deleteById(postId);
    }

    public SearchHits<DiscussPost> search(String keyword, int current, int limit){
        NativeSearchQuery build = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.multiMatchQuery(keyword, "title", "content")) //查询的关键词
                .withSort(SortBuilders.fieldSort("type").order(SortOrder.DESC))//设置第一优先的排序
                .withSort(SortBuilders.fieldSort("score").order(SortOrder.DESC)) //第二优先排序
                .withSort(SortBuilders.fieldSort("createTime").order(SortOrder.DESC))
                .withPageable(PageRequest.of(current, limit))//分页的信息，从第0页开始，每页10个数据
                .withHighlightFields(//对高亮数据的定义，匹配到的哪些类型数据加高亮  前后标签加什么
                        new HighlightBuilder.Field("title").preTags("<em>").postTags("</em>"),
                        new HighlightBuilder.Field("content").preTags("<em>").postTags("</em>")
                ).build();
        SearchHits<DiscussPost> search = elasticsearchRestTemplate.search(build, DiscussPost.class);


        for (SearchHit<DiscussPost> searchHit : search) {
            Map<String, List<String>> fields = searchHit.getHighlightFields();//获取当前高亮显示
            if (!fields.isEmpty()) {
                //对查询的标题和内容的高亮域进行设置
                //注意高亮域有多段，每次只获取第一段的高亮域，因为搜索的内容是不完全显示的
                searchHit.getContent().setTitle(fields.get("title") == null ? searchHit.getContent().getTitle() : fields.get("title").get(0));
                searchHit.getContent().setContent(fields.get("content") == null ? searchHit.getContent().getContent() : fields.get("content").get(0));
            }
        }
        return search;
    }
}
